package com.cheyunkeji.er.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cheyun.netsalev3.MyApplication;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyunkeji.er.adapter.MyBaseAdapter;
import com.cheyunkeji.er.adapter.citymodel.CarBrandSortAdapter;
import com.cheyunkeji.er.app.UserInfoManager;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.evaluate.CarInfo;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.model.CarBrandModel;
import com.cheyunkeji.er.utils.CarBrandPinyinComparator;
import com.cheyunkeji.er.utils.PinyinComparator;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.cityview.SideBar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

public class SelectCarBrandActivity extends BaseActivity
    implements AdapterView.OnItemClickListener, SideBar.OnTouchingLetterChangedListener {

  private static final int LIST_TYPE_CAR_BRAND = 0;
  private static final int LIST_TYPE_SHOP_PROPERTY = 1;

  @BindView(R.id.v_topbar)
  TopBar vTopbar;

  @BindView(R.id.lv_content)
  ListView lvContent;

  @BindView(R.id.activity_select_car_brand)
  LinearLayout activitySelectCarBrand;

  @BindView(R.id.sidebar)
  SideBar sideBar;

  private CarBrandSortAdapter adapter;
  private int selectType;

  private ArrayList<String> shopPropertyList;
  private ShopPropertyAdapter shopPropertyAdapter;

  private List<CarInfo.CarBrand> brandListData;
  private ArrayList<CarBrandModel> modelList;

  @Override
  protected void init() {

    setContentView(R.layout.er_activity_select_car_brand);
    ButterKnife.bind(this);
  }

  @Override
  protected void initView() {

    vTopbar.setLeftBack();
  }

  @Override
  protected void initData() {

    selectType = getIntent().getIntExtra("LIST_TYPE", LIST_TYPE_CAR_BRAND);

    if (selectType == LIST_TYPE_CAR_BRAND) {
      vTopbar.setTitle("车辆品牌");
      modelList = new ArrayList<>();
      adapter = new CarBrandSortAdapter(this, modelList);
      lvContent.setAdapter(adapter);
      lvContent.setOnItemClickListener(this);
      loadCarBrandList();
    } else if (selectType == LIST_TYPE_SHOP_PROPERTY) {

      vTopbar.setTitle("商家性质");
      shopPropertyList = new ArrayList<>();
      shopPropertyAdapter = new ShopPropertyAdapter(shopPropertyList, this);
      lvContent.setAdapter(shopPropertyAdapter);
      lvContent.setOnItemClickListener(this);
      loadShopPropertyList();
    }
  }

  /** 加载车商性质列表 */
  private void loadShopPropertyList() {

    HashMap<String, String> params = new HashMap<>();
    params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
    params.put("field", "ch_ctype");

    ApiClient.postForm(
        HttpConstants.GET_SHOP_PROPERTY_PRE_SELECT_CHANNEL,
        params,
        new StringCallback() {

          @Override
          public void onError(Call call, Exception e, int id) {

            if (e instanceof UnknownHostException || e instanceof SocketException) {
              SToast.show(R.string.tip_network_error, Gravity.CENTER);
              return;
            }
          }

          @Override
          public void onResponse(String response, int id) {

            try {

              JSONObject obj = new JSONObject(response);

              if (obj.optInt("code") == 1) {

                String stringArray = obj.optJSONObject("data").optString("ch_ctype");
                List<String> stringList =
                    new Gson().fromJson(stringArray, new TypeToken<List<String>>() {}.getType());
                shopPropertyList.addAll(stringList);
                shopPropertyAdapter.notifyDataSetChanged();

              } else {

                SToast.show(obj.optString("msg"));
              }

            } catch (JSONException e) {
              e.printStackTrace();
            }
          }

          @Override
          public void onBefore(Request request, int id) {
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            dismissDialog();
          }
        });
  }

  private void loadCarBrandList() {

    HashMap<String, String> params = new HashMap<>();
    params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());

    ApiClient.postForm(
        HttpConstants.PRE_CHANNEL_SELECT_GET_CAR_BRAND_LIST,
        params,
        new RespCallback<List<CarInfo.CarBrand>>() {

          @Override
          protected void onRequestFailed(String msg) {

            SToast.show(msg);
          }

          @Override
          protected void onSuccess(List<CarInfo.CarBrand> data) {

            setBrandListData(data);
          }

          @Override
          public void onBefore(Request request, int id) {
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            dismissDialog();
          }
        });
  }

  private void setBrandListData(List<CarInfo.CarBrand> data) {

    if (null == data) return;

    brandListData = data;
    modelList = new ArrayList<>();

    ArrayList<String> letterList = new ArrayList<>();

    for (int i = 0; i < brandListData.size(); i++) {

      if (brandListData.get(i).getFletter().matches("[A-Z]")
          && !letterList.contains(brandListData.get(i).getFletter())) {
        letterList.add(brandListData.get(i).getFletter());
      }

      CarBrandModel model = new CarBrandModel();
      model.setName(brandListData.get(i).getTitle());
      model.setInitial(brandListData.get(i).getFletter());
      model.setId(brandListData.get(i).getId());
      modelList.add(model);
    }

    Collections.sort(letterList);
    sideBar.setIndexText(letterList);
    sideBar.setTextColor(Color.parseColor("#35404d"));
    sideBar.setVisibility(View.VISIBLE);

    Collections.sort(brandListData, new CarBrandPinyinComparator());

    Collections.sort(modelList, new PinyinComparator());

    adapter = new CarBrandSortAdapter(this, modelList);
    lvContent.setAdapter(adapter);

    sideBar.setOnTouchingLetterChangedListener(this);
    lvContent.setOnItemClickListener(this);
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = new Intent();
    if (selectType == LIST_TYPE_CAR_BRAND) {
      CarBrandModel model = modelList.get(position);
      intent.putExtra(
          "data", new CarInfo.CarBrand(model.getId(), model.getName(), model.getInitial()));
    } else if (selectType == LIST_TYPE_SHOP_PROPERTY) {
      Bundle bundle = new Bundle();
      bundle.putString(Constants.SHOPE_PROPERTY_NAME, shopPropertyList.get(position));
      bundle.putInt(Constants.SHOP_PROPERTY_INDEX, position);
      intent.putExtra("data", bundle);
    }
    setResult(RESULT_OK, intent);
    MyApplication.getInstance().removeActivity(this.getClass());
  }

  @Override
  public void onTouchingLetterChanged(String s) {

    // 该字母首次出现的位置
    int position = adapter.getPositionForSection(s.charAt(0));
    if (position != -1) {
      lvContent.setSelection(position);
    }
  }

  class ShopPropertyAdapter extends MyBaseAdapter {

    public ShopPropertyAdapter(ArrayList<String> dataList, Context context) {
      super(dataList, context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

      final ViewHolder holder;
      if (convertView == null) {
        convertView =
            LayoutInflater.from(context)
                .inflate(R.layout.er_car_source_city_selector_lv_item, null);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
      } else {
        holder = (ViewHolder) convertView.getTag();
      }

      if (position % 2 != 0) convertView.setBackgroundColor(Color.parseColor("#fbfbfb"));
      else convertView.setBackgroundColor(Color.parseColor("#ffffff"));

      String itemBean = (String) dataList.get(position);
      holder.tvCityName.setText(itemBean);

      return convertView;
    }

    class ViewHolder {
      @BindView(R.id.tv_city_name)
      TextView tvCityName;

      ViewHolder(View view) {
        ButterKnife.bind(this, view);
      }
    }
  }

  class CarBrandListAdapter extends MyBaseAdapter {

    public CarBrandListAdapter(ArrayList<CarInfo.CarBrand> dataList, Context context) {
      super(dataList, context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

      final ViewHolder holder;
      if (convertView == null) {
        convertView =
            LayoutInflater.from(context)
                .inflate(R.layout.er_car_source_city_selector_lv_item, null);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
      } else {
        holder = (ViewHolder) convertView.getTag();
      }

      if (position % 2 != 0) convertView.setBackgroundColor(Color.parseColor("#fbfbfb"));
      else convertView.setBackgroundColor(Color.parseColor("#ffffff"));

      CarInfo.CarBrand itemBean = (CarInfo.CarBrand) dataList.get(position);
      holder.tvCityName.setText(itemBean.getTitle());

      return convertView;
    }

    class ViewHolder {
      @BindView(R.id.tv_city_name)
      TextView tvCityName;

      ViewHolder(View view) {
        ButterKnife.bind(this, view);
      }
    }
  }
}
